package calao;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Locale;
import java.util.Properties;

import calao.client.DesktopProperty;
import static calao.util.Logger.*;

class DesktopPage 
extends HtmlPage
{
	
	final static HashSet<String> desktopClientPropKeys = new HashSet<String>();

	final static String JAVASCRIPT_TYPE = "text/javascript";
		
	static {
		for (Field field : DesktopProperty.class.getFields()) {
			if (Modifier.isStatic(field.getModifiers())) {
				try {
					desktopClientPropKeys.add((String)field.get(null));
				} catch (Exception e) {
					log(e);
				}
			}
		}
	}
	
	final private String desktopName;
	final private Properties properties = new Properties();
	
	private Locale locale;

	DesktopPage(String desktopName)
	{
		this.desktopName = desktopName;
	}
	
	void setProperty(String name, String value)
	{
		properties.setProperty(name, value);
	}
	
	void setDesktopProperties(Properties properties)
	{
		for (Object name : properties.keySet()) {
			if (desktopClientPropKeys.contains(name)) {
				setProperty("desktop."+name, properties.getProperty((String)name));
			}
		}		
	}
			
	void setLocale(Locale locale)
	{
		this.locale = locale;
	}

	void writeHead()
	throws IOException
	{
		if (locale!=null) writeMeta("gwt:property", "locale="+locale);
		writeProperties();
	}

	void writeProperties()
	throws IOException
	{
		for (Object name : properties.keySet()) {
			String value = (String)properties.get(name);
			writeMeta("calao:property", value!=null? name+"="+value : (String)name);
		}
	}
	
	void writeBody()
	throws IOException
	{
		includeScript(ScriptType.JAVASCRIPT, desktopName+".nocache.js");
		startElement("iframe", "src", "javascript:''",
				"id", "__gwt_historyFrame", "style", "width:0;height:0;border:0");
		endElement();
	}
	
}
